package com.kyub.spring.gears.namespace;

import org.w3c.dom.Element;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.PropertyValue;
import org.springframework.util.xml.DomUtils;

import java.util.List;
import java.util.Iterator;

import com.kyub.spring.gears.model.FileLayout;
import com.kyub.spring.gears.model.CustomFieldLayout;

public class FormFiledDelegateParser {





        public void parse(Element pojoElement, AbstractBeanDefinition pojoBeanDefinition) {
            final List formFileds = DomUtils.getChildElementsByTagName(pojoElement, "formFields");
            if (formFileds.size() > 0) {
                ManagedList formFiledsList = new ManagedList(formFileds.size());

                Iterator<Element> formFieldsIterator = DomUtils.getChildElementsByTagName((Element) formFileds.get(0), "formField").iterator();

                while (formFieldsIterator.hasNext()) {
                    final Element formElement = formFieldsIterator.next();
                    formFiledsList.add(formElement.getAttribute("name"));

                }
                formFieldsIterator = DomUtils.getChildElementsByTagName((Element) formFileds.get(0), "fileFormField").iterator();

                while (formFieldsIterator.hasNext()) {
                    final Element formElement = formFieldsIterator.next();

                    RootBeanDefinition fileFormFiled = new RootBeanDefinition(FileLayout.class);
                    fileFormFiled.getPropertyValues().addPropertyValue("refPropertyName", formElement.getAttribute("name"));
                    fileFormFiled.getPropertyValues().addPropertyValue("persistPath", formElement.getAttribute("persistPath"));
                    fileFormFiled.getPropertyValues().addPropertyValue("mimeType", formElement.getAttribute("mimeType"));


                    formFiledsList.add(fileFormFiled);


                }

                 formFieldsIterator = DomUtils.getChildElementsByTagName((Element) formFileds.get(0), "customFormField").iterator();

                while (formFieldsIterator.hasNext()) {
                    final Element formElement = formFieldsIterator.next();

                    RootBeanDefinition fileFormFiled = new RootBeanDefinition(CustomFieldLayout.class);
                    fileFormFiled.getPropertyValues().addPropertyValue("refPropertyName", formElement.getAttribute("name"));
                    fileFormFiled.getPropertyValues().addPropertyValue("widgetUri", formElement.getAttribute("widgetUri"));

                    formFiledsList.add(fileFormFiled);


                }



                pojoBeanDefinition.getPropertyValues().addPropertyValue(new PropertyValue("formFields", formFiledsList));


            }
        }

}